package com.mk.sso.handler;

import com.mk.sso.sdk.result.ResultEnum;
import com.mk.sso.sdk.result.ReturnT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ReturnT handle(MethodArgumentNotValidException e) {
        return parseBindingResult(e.getBindingResult());
    }


    @ExceptionHandler(BindException.class)
    public ReturnT validExceptionHandler(BindException e) {
        return parseBindingResult(e.getBindingResult());
    }


    private ReturnT parseBindingResult(BindingResult bindingResult){
        ReturnT returnT = null;

        if (bindingResult.hasErrors()) {
            //获取参数校验错误集合
            ObjectError objectError = bindingResult.getAllErrors().get(0);
            FieldError fileError = (FieldError) objectError;

            returnT = new ReturnT();
            returnT.setCode(ResultEnum.FAILE.code);
            returnT.setMsg(String.format("%s%s", fileError.getField(), fileError.getDefaultMessage()));
        }

        return returnT;
    }


    @ExceptionHandler(value = Exception.class)
    public ReturnT exceptionHandler(Exception e) throws Exception {
        log.error(e.getMessage(), e);
        return ReturnT.failure();
    }
}
